const fs = require('fs');
const path = require('path');
const pdf2image = require('pdf2image');

const inputFolder = './input'; // PDF文件所在的文件夹
const outputFolder = './output'; // 转换后的PNG文件存放的文件夹

fs.readdir(inputFolder, (err, files) => {
  if (err) {
    console.error('读取文件夹失败：', err);
    return;
  }

  files.forEach((file) => {
    if (path.extname(file).toLowerCase() === '.pdf') {
      const pdfPath = path.join(inputFolder, file);
      const outputPath = path.join(outputFolder, path.basename(file, '.pdf') + '.png');

      fs.createReadStream(pdfPath)
        .pipe(pdf2image({ path: pdfPath }))
        .then((images) => {
          images.forEach((image) => {
            image.png({ quality: 100 }); // 将图像质量设置为100%
            fs.writeFileSync(outputPath, image); // 将图像保存为PNG文件
          });
        })
        .catch((error) => {
          console.error('转换PDF为PNG时出错：', error);
        });
    }
  });
});
